package com.henry.base.singleton;

import java.io.Serializable;

/**
 * 1.序列化会破坏单例模式，每次反序列化一个序列化的对象实例都会创建一个新的实例
 * 2.使用反射强行调用私有构造器
 *
 * 解决方案如下
 */
public class SingletonHungrySerialize implements Serializable{

    private static SingletonHungrySerialize instance = new SingletonHungrySerialize();
    private static volatile boolean flag = true;

    private SingletonHungrySerialize() {
        if (flag) {
            flag = false;
        } else {
            throw new RuntimeException("The instance already exists!");
        }
    }

    public static SingletonHungrySerialize getInstance() {
        return instance;
    }

    //反序列化时直接返回当前instance对象
    private Object readResolve() {
        return instance;
    }
}
